package net.matt2000.android.search.wp;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.SearchManager;
import android.app.SearchManager.OnDismissListener;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources.NotFoundException;
import android.net.Uri;
import android.os.Bundle;

public class SearchActivity extends Activity implements OnDismissListener{

	static final String LANGUAGE = "language";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Intent intent = getIntent();
        String language = intent.getStringExtra(LANGUAGE);
        int languageNumber = -1;
        if (language != null && (languageNumber=SuggestionProvider.getLanguageNumber(this, language)) != -1) {
        	ComponentName componentName = new ComponentName(this.getPackageName(), getResources().getStringArray(R.array.searchable_activity)[languageNumber]);
        	SearchManager sm = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        	sm.setOnDismissListener(this);
        	sm.startSearch(null, false, componentName, null, false);
        }

	}

	static void search(Context context, String language, String query) {
		int languageNumber = SuggestionProvider.getLanguageNumber(context, language);
		if (languageNumber==-1) { // get the language from the context
			languageNumber = SuggestionProvider.getLanguageNumber(context);
			if (languageNumber==-1)
				return;
		}
		String url = context.getResources().getStringArray(R.array.search_url)[languageNumber];
		try {
			url = url.replaceAll(Pattern.quote(context.getResources().getStringArray(R.array.search_term)[languageNumber]), URLEncoder.encode(query,"UTF-8"));
			Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
			context.startActivity(intent);
		} catch (NotFoundException e) {
			// do nothing
		} catch (UnsupportedEncodingException e) {
			// do nothing
		}
		
	}

	public void onDismiss() {
//		finish();
		
	}

}
